import axios, { AxiosResponse } from 'axios'
import { notification, Modal, message } from 'antd'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { tansParams, blobValidate } from '@/utils/helper'
import cache from '@/plugins/cache'
import { saveAs } from 'file-saver'
import useUserStore from '@/store/modules/user'
import {ssoLoginTs} from "@/api/login/ssoLogin";
// import { useNavigate } from 'react-router-dom';

const errorCode = {
  '401': '认证失败，无法访问系统资源',
  '403': '当前操作没有权限',
  '404': '访问资源不存在',
  'default': '系统未知错误，请反馈给管理员'
}

let downloadLoadingInstance;
export let isRelogin = { show: false };

//dev
// const SSO_SERVER_WEB_TS = "https://login.microsoftonline.com/7ba64ac2-8a2b-417e-9b8f-fcf8238f2a56/oauth2/v2.0/authorize?client_id=91a3070e-2db5-4f77-b47e-edd5fb14f5a0&response_type=code&scope=openid&redirect_uri=https://cpsrdev.kenvue.com/index"
//qa
// const SSO_SERVER_WEB_TS = "https://login.microsoftonline.com/7ba64ac2-8a2b-417e-9b8f-fcf8238f2a56/oauth2/v2.0/authorize?client_id=6017e89b-3d90-467e-a73d-84e5335ec67a&response_type=code&scope=openid&redirect_uri=https://cpsrqa.kenvue.com/index"
//prod rrd
const SSO_SERVER_WEB_TS='https://login.microsoftonline.com/7ba64ac2-8a2b-417e-9b8f-fcf8238f2a56/oauth2/v2.0/authorize?client_id=1f7db451-f2cb-4aef-973b-be78266c12b1&response_type=code&scope=openid&redirect_uri=https://cpsrrnd.kenvue.com/index'

const getQueryVariable=(variable)=> {
  let url = decodeURIComponent(window.location.search)
  let query = url.substring(1);
  console.log(query,'query')
  let vars = query.split("?");
  for (let i = 0; i < vars.length; i++) {
      let pair = vars[i].split("=");
      if (pair[0] == variable) { return pair[1]; }
  }
  return (false);
}

const SSO = ()=>{
  console.log("SSO")
  const ssoCode = getQueryVariable("code")
  console.log(ssoCode,"code")
  if(ssoCode){
    //用授权码，向自己后台进行请求登录
    ssoLoginTs(ssoCode).then((res) => {
        console.log(res,'codedata')
        // setToken(res.data.token)
        // setAccessToken(res.data.accessToken)
        setToken(res.data.data.token)
        location.href = '/';
    }).catch((res) => {
        console.log("异常发生",res)
        alert("This user is already logged in and cannot log in again!") 
        //授权码可能过期,验证异常，再去统一登录页面获取一次性使用的授权码
        // window.location.href = SSO_SERVER_WEB_TS
    });

}else{
    window.location.href = SSO_SERVER_WEB_TS
}
}

// axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 100000
})

// request拦截器
service.interceptors.request.use(config => {
  // 是否需要设置 token
  const isToken = (config.headers || {} as any).isToken === false
  // 是否需要防止数据重复提交
  const isRepeatSubmit = (config.headers || {} as any).repeatSubmit === false
  if (getToken() && !isToken) {
    config.headers['Authorization'] = 'Bearer ' + getToken()
    // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  // get请求映射params参数
  if (config.method === 'get' && config.params) {
    let url = config.url + '?' + tansParams(config.params);
    url = url.slice(0, -1);
    config.params = {};
    config.url = url;
  }
  if (!isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
    const requestObj = {
      url: config.url,
      data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
      time: new Date().getTime()
    }
    const sessionObj = cache.session.getJSON('sessionObj')
    if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
      cache.session.setJSON('sessionObj', requestObj)
    } else {
      const s_url = sessionObj.url;                // 请求地址
      const s_data = sessionObj.data;              // 请求数据
      const s_time = sessionObj.time;              // 请求时间
      const interval = 0;                       // 间隔时间(ms)，小于此时间视为重复提交
      if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
        const message = '数据正在处理，请勿重复提交';
        console.warn(`[${s_url}]: ` + message)
        return Promise.reject(new Error(message))
      } else {
        cache.session.setJSON('sessionObj', requestObj)
      }
    }
  }
  return config
}, error => {
  console.log(error)
  Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use((res) => {
  // 未设置状态码则默认成功状态
  const code = res.data.code || 200;
  // 获取错误信息
  const msg = errorCode[code] || res.data.msg || errorCode['default']
  // 二进制数据则直接返回
  if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
    return Promise.resolve({ success: true, data: res.data, code: code, message: msg }) as any
  }
  if (code === 401) {

    const ssoCode = getQueryVariable("code")
    console.log(ssoCode,'ssoCode')
    if(ssoCode){
      SSO()
    }else{
      if (!isRelogin.show) {
        isRelogin.show = true;
        // message.warning('登录状态已过期，正在跳转到登录页面...');  
        // 设置一个短暂的延迟以确保消息能够被用户看到  
        // 这里的延迟时间可以根据需要调整  
       
        Modal.confirm({
          title: '系统提示',
          content: '登录状态已过期，您可以继续留在该页面，或者重新登录',
          okText: '重新登录',
          cancelText: '取消',
          type: 'warning',
          onOk: (close) => { 
              isRelogin.show = false
              // 在延迟后执行页面跳转  
              useUserStore.getState().logOut().then(() => {
                  // location.href = '/login';
                  window.location.href = SSO_SERVER_WEB_TS
                  close();
                }).catch(()=>{
                  
                })
                return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
          },
          onCancel: () => {
            isRelogin.show = false;
            close();
          }
        }
        )
      }
    }
   
  } else if (code === 500) {
    message.error(msg)
    return Promise.resolve({ success: false, data: res.data, code: code, message: msg }) as any
  } else if (code !== 200) {
    notification.error({
      message: msg
    })
    return Promise.resolve({ success: false, data: res.data, code: code }) as any
  } else {
    return Promise.resolve({ success: true, data: res.data, code: code }) as any
  }
},
  error => {
    console.log('err' + error)
    let { message } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    }
    else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    }
    else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    message.error({
      content: message,
      duration: 5 * 1000
    })
    return Promise.resolve({ success: false, data: error, message }) as any
  }
)

// 通用下载方法
export function download(url, params, filename) {
  downloadLoadingInstance = message.loading({ content: "正在下载数据，请稍候" })
  return service.post(url, params, {
    transformRequest: [(params) => { return tansParams(params) }],
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    responseType: 'blob'
  }).then(async ({ success, data }) => {
    if (success) {
      const isLogin = await blobValidate(data);
      if (isLogin) {
        const blob = new Blob([data])
        saveAs(blob, filename)
      } else {
        const resText = await data.text();
        const rspObj = JSON.parse(resText);
        const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
        message.error(errMsg);
      }
      downloadLoadingInstance.destroy();
    } else {
      message.error('下载文件出现错误，请联系管理员！')
      downloadLoadingInstance.close();
    }
  })
}

// 传参为数组的下载方法
export function downloadArr(url, params, filename) {
  console.log(params,'params')
  downloadLoadingInstance = message.loading({ content: "正在下载数据，请稍候" })
  return service.post(url, params, {
    headers: { 'Content-Type': 'application/json' },
    responseType: 'blob'
  }).then(async ({ success, data }) => {
    if (success) {
      const isLogin = await blobValidate(data);
      if (isLogin) {
        const blob = new Blob([data])
        saveAs(blob, filename)
      } else {
        const resText = await data.text();
        const rspObj = JSON.parse(resText);
        const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
        message.error(errMsg);
      }
      downloadLoadingInstance.destroy();
    } else {
      message.error('下载文件出现错误，请联系管理员！')
      downloadLoadingInstance.close();
    }
  })
}

export default service
